package utils;

import book.Book;
import com.bit.utils.FileUtils;
import constant.Constant;

import java.io.IOException;
import java.time.LocalDate;



/**
 * 读取文件：我们在初始化图书馆类的时候里面的书籍等等相关信息想要永久保存
 * 在实例化图书馆之后，加载文件当中的内容，对文件进行操作（上架更新图书等等），将操作之后的数据再次更新文件
 */

public class AnalyzingBook {

    /**
     * 通过此函数进行将数据信息写入文件当中
     * @param books
     * @param filename
     */
    public void storeObject(Book[] books, String filename) throws IOException {
        //System.out.println("将数据写入文件当中");
        int booksUseLen = 0;
        for (int i = 0; i < books.length; i++) {
            if(books[i] != null){
                booksUseLen++;
            }
        }
        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < booksUseLen; i++) {  //这里的每一个book[i]其实是一个对象的引用，我们应该解析对象里面的属性等等，存储的大概是这样的1，"java", "gaobo", "编程"
            if(books[i] != null){
                jsonArray.append(books[i].toJSON());
                if (i != booksUseLen-1) {
                    //⼀本书籍完成后以\n进⾏分割
                    jsonArray.append("\n");
                }
            }
        }
        FileUtils.writeFile(jsonArray.toString(),filename);
    }
    /**
     * 通过次函数将文件中的数据读入程序,程序当中的一个书籍引用数组
     * @param filename
     */
    public Book[] loadObject(String filename) throws IOException {
        //System.out.println("将文件信息写入程序数组当中");
        String content = FileUtils.readFile(filename);
        //从文件中读取数据到内存中
        if(content == null || content.isEmpty()){
            System.out.println("File is empty or does't exist: " + filename);
            return null;
        }

        //使用\n作为分隔符进行每一本书也就是一行字符串进行分割
        String[] bookJsonStrings = content.split("\n");

        //把对应的字符串封装组装成书籍对象
        Book[] bookList = new Book[bookJsonStrings.length];
        for (int i = 0; i < bookJsonStrings.length; i++) {
            Book book = parseBookJson(bookJsonStrings[i]);
            bookList[i] = book;
        }
        return bookList;
    }

    /**
     * 通过此函数将我们书籍的具体信息json化其实就是变得更加容易操作，有规律的存放
     * @return 返回一个书的对象
     * private修饰表明此函数仅为本类服务
     */

    //这里的json其实就是每一本书，0，java，gaobo。。。。。我们需以逗号分割
    private Book parseBookJson(String json){

        if(json.isEmpty()){
            return null;
        }
        String[] ret = json.split(",");

        int bookId = Integer.parseInt(ret[0]);
        String title = ret[1];
        String author = ret[2];
        String category = ret[3];
        int publishYear = Integer.parseInt(ret[4]);
        boolean isBorrowed = Boolean.parseBoolean(ret[5]);
        int borrowCount = Integer.parseInt(ret[6]);
        LocalDate shelfDate = LocalDate.parse(ret[7]);

        if(title != null && author != null && category != null && shelfDate != null){
            Book book = new Book(title,author,category,shelfDate,publishYear);
            book.setBookId(bookId);
            book.setBorrowCount(borrowCount);
            book.setBorrowed(isBorrowed);
            return book;
        }
        return null;

    }

//    public static void main(String[] args) throws IOException{
//        Book[] books = new Book[4];
//        books[0] = new Book("java", "gaobo", "编程", LocalDate.of(2023, 9, 24),1994 );
//        books[1] = new Book("mysql", "lisi", "编程", LocalDate.of(2024, 2, 10),1999);
//        books[2] = new Book("php", "gaobo", "编程",  LocalDate.of(2023, 9, 23),2020);
//        books[3] = new Book("西游记", "吴承恩", "⼩说", LocalDate.of(2023, 9, 23),2024);
//
//        AnalyzingBook analyzingBook = new AnalyzingBook();
//        String filename = Constant.ALL_BOOK_FILE_NAME;
//        analyzingBook.storeObject(books,filename);
//        Book[] ret = analyzingBook.loadObject(filename);
//
//        for (int i = 0; i < ret.length; i++) {
//            System.out.println(ret[i]);
//        }
//    }

}
